﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Levfier.GUI.EditorControls.Chains
{
    /// <summary>
    /// 2点間に線を生成する
    /// </summary>
    [Serializable]
    public class ChainLineCreater : ILineCreatable
    {
        /// <summary>
        /// 三角形の高さ
        /// </summary>
        private static readonly int TriangleHeight = 5;

        /// <summary>
        /// 三角形の幅
        /// </summary>
        private static readonly int TriangleWidth = 5;

        /// <summary>
        /// 通常時のブラシ
        /// </summary>
        public Brush Stroke{ get; set; }

        /// <summary>
        /// 2点間を繋ぐラインを生成する
        /// </summary>
        /// <param name="upper">上流のポイント</param>
        /// <param name="lower">下流のポイント</param>
        /// <returns>描画オブジェクトのコレクション</returns>
        public IEnumerable<UIElement> CreateLine(Point upper, Point lower)
        {
            //リターン用リスト
            IList<UIElement> elements = new List<UIElement>();

            //メインの線を作成
            Polyline line = new Polyline();
            line.Points.Add(upper);
            line.Points.Add(lower);
            line.Stroke = this.Stroke;
            elements.Add(line);

            //方向を示す三角形を作成
            Point p = new Point( (upper.X+ lower.X) / 2.0d, (upper.Y + lower.Y) / 2.0d );
            Polygon polygon = new Polygon();
            polygon.Points.Add(p);
            double angle = Math.Atan2(lower.Y - upper.Y, lower.X - upper.X);
            double x = -TriangleWidth * Math.Cos(angle) - TriangleHeight * Math.Sin(angle);
            double y = -TriangleWidth * Math.Sin(angle) + TriangleHeight * Math.Cos(angle);
            polygon.Points.Add(new Point(p.X + x, p.Y + y));
            x = -TriangleWidth * Math.Cos(angle) + TriangleHeight * Math.Sin(angle);
            y = -TriangleWidth * Math.Sin(angle) - TriangleHeight * Math.Cos(angle);
            polygon.Points.Add(new Point(p.X + x, p.Y + y));
            polygon.Fill = this.Stroke;
            elements.Add(polygon);

            return elements;
        }
    }
}
